#include <iostream>
#include <ctime>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"
#include "Log.hpp"

const string &oper = "+-*/%$#";
Log lg;

void Usage(const std::string &proc)
{
    std::cout << "\n\r"
              << "Usage:" << proc << " ip port " << std::endl;
}

// ./ClientCal ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }
    uint16_t serverport = std::stoi(argv[2]);
    std::string serverip = argv[1];

    Sock sk;
    sk.Socket();

    bool n = sk.Connect(serverip, serverport);
    if (!n)
        exit(1);

    srand(time(nullptr) ^ getpid());
    std::string inbuffer_info;

    int cnt = 1;
    while (cnt <= 10)
    {
        int x = rand() % 100 + 1;
        usleep(9999);
        int y = rand() % 100;
        usleep(4321);
        char op = oper[rand() % oper.size()];
        std::cout << "=============第" << cnt << "次测试 "
                  << "===============" << std::endl;

        Request req(x, y, op);
        std::string package;
        req.Serialize(&package);   //"x op y"
        package = Encode(package); //"len""\n""x op y""\n"

        std::cout << "新请求构建完成:  " << x << op << y << "=?" << std::endl;
        write(sk.Getfd(), package.c_str(), package.size());

        char buffer[1024];
        int n = read(sk.Getfd(), buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            inbuffer_info += buffer; //"len""\n""result errcode""\n"
            cout << inbuffer_info << endl;

            Response resp(0, 0);
            std::string content;
            n = Decode(inbuffer_info, &content);
            if (!n)
                exit(2);

            n = resp.Deserialize(content);
            if (!n)
                exit(3);

            std::cout << "结果响应完成, result: " << resp.result << ", code: " << resp.errcode << std::endl;
        }

        std::cout << "=================================================" << std::endl;

        sleep(1);
        cnt++;
    }

    return 0;
}